package com.hyfrogx.modules.sys.service.impl;

import com.hyfrogx.common.utils.Constant;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import com.hyfrogx.modules.sys.entity.SysUserTokenEntity;
import com.hyfrogx.modules.sys.service.ShiroService;
import com.hyfrogx.modules.sys.service.SysMenuService;
import com.hyfrogx.modules.sys.service.SysUserService;
import com.hyfrogx.modules.sys.entity.SysMenuEntity;
import com.hyfrogx.modules.sys.oauth2.TokenGenerator;
import com.hyfrogx.modules.sys.service.SysUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * TODO ShiroService实现类
 *
 * @author crazypenguin
 * @version 1.0.0
 * @createdate 2019/1/2
 */
@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        // 系统管理员，拥有最高权限，写死ID-1
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuService.list(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserService.queryAllPerms(userId);
        }
        // 用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenService.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        return sysUserService.getById(userId);
    }

    	@Override
	public SysUserEntity queryByUserName(String username) {
		return sysUserService.queryByUserName(username);
	}

	@Override
	public String createToken() {
		return TokenGenerator.generateValue();
	}
}
